package shopping.demo.config.interceptor;

import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import shopping.demo.annotation.ApiIdempotent;
import shopping.demo.exception.token.TokenNotExistException;
import shopping.demo.exception.token.TokenNotValidException;
import shopping.demo.util.TokenUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class IdempotentInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenUtils tokenUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //不是修饰方法则直接放行
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }

        ApiIdempotent apiIdempotent = ((HandlerMethod) handler).getMethodAnnotation(ApiIdempotent.class);
        //说明没有被幂等注解修饰
        if(apiIdempotent == null) {
            return true;
        }

        String token = request.getHeader(TokenUtils.TOKEN_HEADER);
        //无法从请求头部中获取token，说明违法操作
        if(Strings.isBlank(token)) {
           throw new TokenNotValidException();
        }

        if(!tokenUtils.checkToken(token)) {
            throw new TokenNotExistException();
        }

        return true;
    }
}
